from typing import Callable, Coroutine, Any, Tuple, Union

from fastapi import Request, Response
from fastapi.routing import APIRoute

from common.route.route import CustomerBaseRoute
from common.utils.resp import JsonResponse, RC


class TenantBaseAPIRoute(CustomerBaseRoute):
    """
        表示接口都需要tenant_id的cookie表示当前登陆的租户
    """

    async def do_before(self, request, *args, **kwargs) -> Tuple[bool, Union[Response, None]]:
        from common.g.g import G_TENANT_BLOOMFILTER
        tenant_id = request.cookies.get("login_tenant")
        if not tenant_id:
            return False, JsonResponse(code=RC.NEED_LOGIN_TENANT, msg="尚未登陆").to_response()
        exist = await G_TENANT_BLOOMFILTER.exist(f"tenant:{tenant_id}")
        if not exist:
            return False, JsonResponse(code=RC.TENANT_NOT_EXIST, msg="租户不存在").to_response()
        request.state.tenant_id = tenant_id
        return True, None


class ClientTenantBaseAPIRoute(CustomerBaseRoute):

    async def do_before(self, request: Request, *args, **kwargs) -> Tuple[bool, Union[Response, None]]:
        from common.g.g import G_TENANT_BLOOMFILTER
        tenant_id = request.headers.get("X-TENANT-ID")
        if not tenant_id:
            return False, JsonResponse(code=RC.PARAM_ERROR, msg="未知域").to_response()
        exist = await G_TENANT_BLOOMFILTER.exist(f"tenant:{tenant_id}")
        if not exist:
            return False, JsonResponse(code=RC.TENANT_NOT_EXIST, msg="错误的域").to_response()
        request.state.tenant_id = tenant_id
        return True, None

